package com.ljye.jg.ljye.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.ljye.jg.ljye.App;
import com.ljye.jg.ljye.R;
import com.ljye.jg.ljye.bean.Teacher_base;
import com.ljye.jg.ljye.utils.HttpUtils;
import com.ljye.jg.ljye.utils.Utils;
import com.ljye.jg.ljye.view.HeadPic_PopupWindow;
import com.ljye.jg.ljye.view.Sex_PopupWindow;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//基本信息
public class Activity_Essential_info extends Activity {
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    protected static Uri tempUri;
    HeadPic_PopupWindow menuWindow;
    private OkHttpClient client;
    private String imagePath;//图片地址
    private String imgPath;//图片地址
    private String filename;//文件名字

    private ImageView back;//返回
    private TextView Consultation;//保存
    private LinearLayout headPortrait;//头像
    private EditText name;//姓名
    private EditText nickname;//昵称
    private TextView sex;//性别
    private TextView yesr;//教龄
    private EditText phone;//电话
    private EditText qq;//qq
    private EditText postcode;//邮编
    private LinearLayout sexThis;//性别 点击
    private LinearLayout yesrThis;//教龄 点击
    private CircleImageView headImg;//头像
    private String token;
    private Gson gson;
    private Teacher_base.DataBean.TeacherBean teacher;//老师数据
    private Sex_PopupWindow sexwindow;
    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo://相机
                    Intent openCameraIntent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    tempUri = Uri.fromFile(new File(Environment
                            .getExternalStorageDirectory(), "image.jpg"));
                    // 指定照片保存到sd卡 image.jpg 是一个临时文件 每次拍照都会被覆盖
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);
                    break;
                case R.id.btn_pick_photo://本地
                    Intent openAlbumIntent = new Intent(
                            Intent.ACTION_GET_CONTENT);
                    openAlbumIntent.setType("image/*");
                    startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                    break;
                default:
                    break;
            }
        }
    };
    private View.OnClickListener sexOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            sexwindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_man://男人
                    sex.setText("男");
                    break;
                case R.id.btn_woman://女人
                    sex.setText("女");
                    break;
                default:
                    break;
            }
        }
    };
    private File file;
    public View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.back://返回
                    finish();
                    break;
                case R.id.Consultation://保存
                    up_date();
                    break;
                case R.id.head_portrait://头像
                    //实例化SelectPicPopupWindow
                    menuWindow = new HeadPic_PopupWindow(Activity_Essential_info.this, itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(Activity_Essential_info.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    //设置layout在PopupWindow中显示的位置

                    break;
                case R.id.sex_this://性别
                    sexwindow = new Sex_PopupWindow(Activity_Essential_info.this, sexOnClick);
                    sexwindow.showAtLocation(Activity_Essential_info.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                    break;
                case R.id.yesr_this://教龄
                    OptionsPickerView options = new OptionsPickerView(Activity_Essential_info.this);
                    final ArrayList<String> list = new ArrayList<>();
                    for (int i = 0; i < 51; i++) {
                        list.add(i + "");
                    }
                    options.setPicker(list);
                    options.setCyclic(false);
                    options.setSelectOptions(1);
                    options.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {
                            yesr.setText(list.get(options1));
                        }
                    });
                    options.show();
                    break;

                default:
                    break;
            }
        }
    };

    public void up_date() {
        if (imagePath != null) {
            // 拿着imagePath上传了
            imgPath = imagePath;
            filename = imgPath.substring(imgPath.lastIndexOf("/") + 1);
            file = new File(imagePath);
            Log.d("Activity_up", imagePath);

        }
        if (file == null) {
            Toast.makeText(this, "请上传头像", Toast.LENGTH_SHORT).show();
            return;
        }
        final String up_name = name.getText().toString().trim();//输入的姓名
        final String up_nickname = nickname.getText().toString().trim();//昵称
        final String up_sex = sex.getText().toString().trim();//sex
        final String up_yesr = yesr.getText().toString().trim();//教龄
        final String up_mobile = phone.getText().toString().trim();//手机号
        final String up_qq = qq.getText().toString().trim();//qq号码
        final String up_email = postcode.getText().toString().trim();//邮箱

        new Thread() {
            @Override
            public void run() {
                RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("avatar", filename, fileBody)
                        .addFormDataPart("mobile", up_mobile)
                        .addFormDataPart("truename", up_name)
                        .addFormDataPart("nickname", up_nickname)
                        .addFormDataPart("sex", up_sex)
                        .addFormDataPart("teachingage", up_yesr)
                        .addFormDataPart("qq", up_qq)
                        .addFormDataPart("email", up_email)
                        .build();

                Request request = new Request.Builder()
                        .url(HttpUtils.PATH + "/base")
                        .addHeader("Accept", HttpUtils.MYAPP)
                        .addHeader("Authorization", "Bearer" + " " + token)
                        .post(body)
                        .build();

                try {
                    Response execute = client.newCall(request).execute();
                    if (execute.isSuccessful()) {
                        String up_string = execute.body().string();
                        Log.d("Activity_up", up_string);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(Activity_Essential_info.this, "上传成功", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_essential_info);

        App application = (App) getApplication();
        client = App.getClient();
        token = application.getToken();
        //初始化控件
        initView();
        //从服务器获取用户数据 并且显示
        getdata();


        back.setOnClickListener(listener);
        Consultation.setOnClickListener(listener);
        headPortrait.setOnClickListener(listener);
        sexThis.setOnClickListener(listener);
        yesrThis.setOnClickListener(listener);


    }

    public void getdata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url(HttpUtils.PATH + "/base")
                            .addHeader("Accept", HttpUtils.MYAPP)
                            .addHeader("Authorization", "Bearer" + " " + token)
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        gson = new Gson();
                        Teacher_base teacher_base = gson.fromJson(string, Teacher_base.class);
                        teacher = teacher_base.getData().getTeacher();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setdata();
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void setdata() {
        if (teacher.getSex() != null) {
            sex.setText(teacher.getSex());//性别
        }
        yesr.setText(teacher.getTeachingage() + "");// 教龄

        if (teacher.getMobile() != null) {
            phone.setHint(Utils.HintText(teacher.getMobile()));//手机号
        }
        if (teacher.getTruename() != null) {
            name.setText(Utils.HintText(teacher.getTruename()));//姓名
        }
        if (teacher.getNickname() != null) {
            nickname.setText(Utils.HintText(teacher.getNickname()));//昵称
        }
        if (teacher.getQq() != null) {
            qq.setText(Utils.HintText(teacher.getQq()));//QQ
        }

        if (teacher.getEmail() != null) {
            postcode.setText(Utils.HintText(teacher.getEmail()));//邮箱
        }

//        if (avatar)
//        Picasso.with(this).load(HttpUtils.PATH+avatar).into(headImg);


    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        Consultation = (TextView) findViewById(R.id.Consultation);
        headPortrait = (LinearLayout) findViewById(R.id.head_portrait);
        name = (EditText) findViewById(R.id.name);
        nickname = (EditText) findViewById(R.id.nickname);
        sex = (TextView) findViewById(R.id.sex);
        yesr = (TextView) findViewById(R.id.yesr);
        phone = (EditText) findViewById(R.id.phone);
        qq = (EditText) findViewById(R.id.qq);
        postcode = (EditText) findViewById(R.id.postcode);
        headImg = (CircleImageView) findViewById(R.id.head_img);
        sexThis = (LinearLayout) findViewById(R.id.sex_this);
        yesrThis = (LinearLayout) findViewById(R.id.yesr_this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case TAKE_PICTURE:
                    startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {

        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param
     * @param
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
//            photo = Utils.toRoundBitmap(photo, tempUri); // 这个时候的图片已经被处理成圆形的了
            headImg.setImageBitmap(photo);
            uploadPic(photo);
        }
    }

    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file，然后得到file的url，做文件上传操作
        // 注意这里得到的图片已经是圆形图片了
        // bitmap是没有做个圆形处理的，但已经被裁剪了

        imagePath = Utils.savePhoto(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));
        Log.e("imagePath", imagePath + "");

    }

    //收起软键盘
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }


}
